package com.horoscope.astrology.zodiac.signs.free.activity

import android.os.Bundle
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.adapter.QuoteAdapter
import com.horoscope.astrology.zodiac.signs.free.bean.QuoteBean
import com.horoscope.astrology.zodiac.signs.free.dao.Quote
import com.horoscope.astrology.zodiac.signs.free.dao.QuoteDao
import com.horoscope.astrology.zodiac.signs.free.database.QuoteDB
import com.horoscope.astrology.zodiac.signs.free.infc.OnItemClickedListener
import com.horoscope.astrology.zodiac.signs.free.utils.EventType
import com.horoscope.astrology.zodiac.signs.free.utils.FlurryEventUtil
import com.horoscope.astrology.zodiac.signs.free.utils.Logger
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_business.ADNativeManager
import com.horoscope.astrology.zodiac.signs.free.view.ViewPagerSnapHelper
import com.jeremyliao.liveeventbus.LiveEventBus
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers


/**
 * 数据是Excel,需要自己制作db文件使用(文字、图片、字体,自己组装),目前16800条数据
 * 总共有60张图片 (0~59)
 * 部分判断 == , >= 60 时，就已经是新数据了 (注意下标!!!)
 * 需求：
 * 1、每次进入页面都要显示上一次所看数据的下一个,即最新数据；
 * 2、初次进入不可滑动,其它时可向左查看历史数据(目前只缓存最新数据前60条)
 */
class QuoteActivity : BaseActivity() {

    private lateinit var mRv: RecyclerView
    private var manager: LinearLayoutManager? = null
    private var adapter: QuoteAdapter? = null
    private var adapterList: MutableList<QuoteBean> = ArrayList()
    private var tempList: MutableList<QuoteBean> = ArrayList()
    private var url = 1

    private var rangeList: MutableList<Quote> = ArrayList()
    private var dao: QuoteDao? = null
    private var db: QuoteDB? = null

    private var scrollItemCount = 0 //滑动次数
    private var currentIndex = 100 // 当前显示的下标

    private var lastItem = 0
    private var lastItemMax = 0 // 区间内浏览的最大下标

    // 记录这一次使用的数据区间
    private var currentRangeStart = 0
    private var currentRangeEnd = 0

    private var isInterOrNative = true  // 判断是哪种类型Ad
    private var nativeAdIndex = 0 // Native广告位置
    private var isShow = false // Native是否显示

    private var num = 0 // 加载多少条History
    private var start = 0 // 从哪里开始加载History

    private var mDetector: GestureDetector? = null
    private val FLIP_DISTANCE = 50f

    companion object {
        private const val NUM_SIX = 6
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_quote)
        intent?.let {
            if (!it.getBooleanExtra("isNotification", false)) {
                FlurryEventUtil.putDataToEvent(EventType.TYPE_APP_OPEND, "type", "Push_Quote")
            }
        }

        // 必现全屏广告A
        activityShowAd("Interstitial_Quote")

        // 初始化此次向数据库查询区间
        currentRangeStart = AppSettingManager.readInt("quote_range_start", 0)
        currentRangeEnd = currentRangeStart + 60

        lastItemMax = if (currentRangeStart > 60) 60 else currentRangeStart

        num = if (currentRangeStart >= 60) 60 else currentRangeStart % 60
        start = if (currentRangeStart > 60) currentRangeStart - 60 else 0
        Logger.error(
            "---",
            "开始的位置=$currentRangeStart \n lastItemMax=$lastItemMax \n num=$num \n start=$start"
        )

        Observable.create(ObservableOnSubscribe<Int?> { emitter ->
            // 获取DB
            db = QuoteDB.get(this@QuoteActivity)
            // 获取表操作类
            dao = db!!.quoteDao()
            // 获取指定区间的数据
            if (currentRangeStart == 0) {
                rangeList = dao!!.getIndexForSixtyData(currentRangeStart)
            } else {
                rangeList = dao!!.getHistoryData(start, num + 60)
                Logger.error(
                    "---",
                    "start=$start----num=$num----currentRangeStart=$currentRangeStart"
                )
            }
            emitter.onNext(1)
            emitter.onComplete()
        }).subscribeOn(Schedulers.io()) //在io执行上述操作
            .observeOn(AndroidSchedulers.mainThread()) //在UI线程执行下面操作
            .subscribe(object : io.reactivex.Observer<Int?> {
                override fun onSubscribe(d: Disposable) {}

                override fun onNext(t: Int) {
                    // 添加数据
                    if (rangeList.isNotEmpty()) {
                        initData(rangeList, adapterList)
                        initView()
                    } else {
                        // 正式版删除代码
                        Logger.error("---", "没取到数据")
                    }
                }

                override fun onError(e: Throwable) {}

                override fun onComplete() {}
            })

        // 判断什么手指滑动方向
        isMove()
    }

    private fun isMove() {
        mDetector = GestureDetector(this, object : GestureDetector.OnGestureListener {
            override fun onSingleTapUp(e: MotionEvent): Boolean {
                // TODO Auto-generated method stub
                return false
            }

            override fun onShowPress(e: MotionEvent) {
                // TODO Auto-generated method stub
            }

            override fun onScroll(
                e1: MotionEvent,
                e2: MotionEvent,
                distanceX: Float,
                distanceY: Float
            ): Boolean {
                // TODO Auto-generated method stub
                return false
            }

            override fun onLongPress(e: MotionEvent) {
                // TODO Auto-generated method stub
            }

            /**
             *
             * e1 The first down motion event that started the fling. e2 The
             * move motion event that triggered the current onFling.
             */
            override fun onFling(
                e1: MotionEvent,
                e2: MotionEvent,
                velocityX: Float,
                velocityY: Float
            ): Boolean {
                if (e1.x - e2.x > FLIP_DISTANCE) {
                    Log.i("MYTAG", "向左滑...")
                    return true
                }
                if (e2.x - e1.x > FLIP_DISTANCE) {
                    Log.i("MYTAG", "向右滑...")
                    return true
                }
                if (e1.y - e2.y > FLIP_DISTANCE) {
                    Log.i("MYTAG", "向上滑...")
                    return true
                }
                if (e2.y - e1.y > FLIP_DISTANCE) {
                    Log.i("MYTAG", "向下滑...")
                    return true
                }
                Log.d("TAG", e2.x.toString() + " " + e2.y)
                return false
            }

            override fun onDown(e: MotionEvent): Boolean {
                // TODO Auto-generated method stub
                return false
            }
        })
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        return mDetector!!.onTouchEvent(event)
    }

    // Adapter 组装数据
    private fun initData(outList: MutableList<Quote>, inList: MutableList<QuoteBean>) {
        outList.forEach {
            inList.add(
                QuoteBean(it.quote_text!!, it.author!!, url, it.img_id!!, it.font!!)
            )
        }
    }

    fun initView() {
        mRv = findViewById(R.id.recycler_view)
        mRv.onFlingListener = null
        ViewPagerSnapHelper().attachToRecyclerView(mRv) // 每次只滑动一张
        manager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        mRv.layoutManager = manager
        adapter = QuoteAdapter(this@QuoteActivity, adapterList)
        adapter!!.setOnItemClickedListener(object : OnItemClickedListener {
            override fun onItemClick(view: View, position: Int, string: String) {
                when (string) {
                    "back" -> finish()
                    "key" -> mRv.scrollToPosition(58)
                }
            }
        })
        mRv.adapter = adapter

        // 跳转到最新数据
        if (currentRangeStart > 60) {
            mRv.scrollToPosition(60)
        } else {
            mRv.scrollToPosition(currentRangeStart)
        }
    }

    override fun onResume() {
        super.onResume()
        try {
            // 存储标识 表示正在浏览Quote
            AppSettingManager.saveInt(1, "Quote_Now")
            LiveEventBus.get("quotePosition", Int::class.java)
                .observeSticky(this@QuoteActivity,
                    androidx.lifecycle.Observer { t ->
                        t?.let {
                            // 判断左右滑
                            if (lastItem > t) {
                                FlurryEventUtil.putDataToEvent(
                                    EventType.TYPE_QUOTE_SLIDE_FRONT, null, null
                                )
                            } else if (lastItem < t) {
                                FlurryEventUtil.putDataToEvent(
                                    EventType.TYPE_QUOTE_SLIDE_BEHIND, null, null
                                )
                                // 滑动到第二张
//                                if (t == 1 && currentRangeStart > 0 && !isHistory) {
//                                    isHistory = true
//                                    // 添加之前浏览的历史数据60条
//                                    addHistoryData()
//                                }
                            }
                            lastItem = t

                            // 判断是否滑到尾部，添加新数据
                            isAddDataToList(t)

                            // 当前区间浏览的最大下标（判断下次最新数据下标）
                            if (t >= lastItemMax) {
                                lastItemMax = t
                            }

                            // 存储下标与当前显示下标比对 计数（判断显示什么类型广告）
                            if (currentIndex != t) {
                                currentIndex = t
                                scrollItemCount += 1
                            }

                            // 是否显示指定类型广告（每6次循环展示全屏/原生）
                            whichAdToShow(t)

                            // 再滑动，将原生广告滑出屏幕，要清除广告，刷新Adapter
                            // 是否添加 & 左右滑动
                            if (isShow && t != nativeAdIndex) {
                                isShow = false
                                adapter!!.removeNativeAd(nativeAdIndex)
                            }

                            Logger.error(
                                "---",
                                "t = $t - currentRangeStart = $currentRangeStart - lastItemMax = $lastItemMax "
                            )
                        }
                    })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun whichAdToShow(itemIndex: Int) {
        if (scrollItemCount == NUM_SIX && isInterOrNative) {
            scrollItemCount = 0
            isInterOrNative = false
            activityShowAd("Interstitial_Quote")
        } else if (scrollItemCount == NUM_SIX && !isInterOrNative) {
            scrollItemCount = 0
            isInterOrNative = true
            val nativeAdBean = ADNativeManager.mInstance.getNativeAdBean("Native_Quote")
            // 是否有可用Ad & 是否显示成功
            if (nativeAdBean != null) {
                if (nativeAdBean.facebookNativeAD != null || nativeAdBean.googleNativeAd != null) {
                    // 插入一条原生广告，刷新Adapter
                    adapter!!.addNativeAd(itemIndex, nativeAdBean)
                    isShow = true
                    // 记录原生广告显示位置
                    nativeAdIndex = itemIndex
                } else {
                    isShow = false
                }
            } else {
                isShow = false
            }
        }
    }

    private fun isAddDataToList(itemIndex: Int) {
        // 判断是否是最后一条数据
        if (itemIndex + 1 == adapter!!.itemCount) {
            // 添加60条数据并刷新
            currentRangeStart += 60
            currentRangeEnd += 60
            Observable.create(ObservableOnSubscribe<Int?> { emitter ->
                rangeList = dao!!.getIndexForSixtyData(currentRangeStart)
                emitter.onNext(1)
                emitter.onComplete()
            }).subscribeOn(Schedulers.io()) //在io执行上述操作
                .observeOn(AndroidSchedulers.mainThread()) //在UI线程执行下面操作
                .subscribe(object : io.reactivex.Observer<Int?> {
                    override fun onSubscribe(d: Disposable) {}

                    override fun onNext(t: Int) {
                        if (rangeList.isNotEmpty()) {
                            initData(rangeList, tempList)
                            adapterList.addAll(tempList)
                            adapter!!.notifyItemRangeInserted(itemIndex + 1, tempList.size)
                            Logger.error(
                                "---",
                                "添加了一次数据=$currentRangeStart \n adapterCount = ${adapter!!.itemCount}"
                            )
                        }
                    }

                    override fun onError(e: Throwable) {}

                    override fun onComplete() {}
                })
        }
    }

    private fun addHistoryData() {
        var addDataList: MutableList<Quote> = ArrayList()
        val addList: MutableList<QuoteBean> = ArrayList()

        Observable.create(ObservableOnSubscribe<Int?> { emitter ->
            addDataList = dao!!.getHistoryData(start, num)
            emitter.onNext(1)
            emitter.onComplete()
        }).subscribeOn(Schedulers.io()) //在io执行上述操作
            .observeOn(AndroidSchedulers.mainThread()) //在UI线程执行下面操作
            .subscribe(object : io.reactivex.Observer<Int?> {
                override fun onSubscribe(d: Disposable) {}

                override fun onNext(t: Int) {
                    if (addDataList.isNotEmpty()) {
                        addList.clear()
                        addDataList.forEach {
                            addList.add(
                                QuoteBean(it.quote_text!!, it.author!!, url, it.img_id!!, it.font!!)
                            )
                        }
                        adapter!!.notifyItemRangeInserted(0, tempList.size)
                    }
                }

                override fun onError(e: Throwable) {}

                override fun onComplete() {}
            })
    }

    override fun onPause() {
        super.onPause()
        // 因为会展示一次全屏广告，这里数据可能还没查询到
        if (rangeList.size > 0 && adapterList.size > 0) {
            // 存储Horoscope_quote要展示的新数据
            AppSettingManager.saveObject<QuoteBean>(adapterList[lastItemMax + 1], "quote_bean")
        }
        // 存储此次浏览在db中的位置(+1的位置)
        if (currentRangeStart <= 16700) {
            if (currentRangeStart > 60 && currentRangeStart % 60 == 0) { // 当前List的最后一个item
                AppSettingManager.saveInt(currentRangeStart, "quote_range_start")
                Logger.error("---", "下一次起始位置=60->$currentRangeStart")
            } else if (currentRangeStart > 60) { // 添加了一次或多次新数据
                AppSettingManager.saveInt(
                    currentRangeStart + lastItemMax % 60 + 1, "quote_range_start"
                )
                Logger.error("---", "下一次起始位置>60->${currentRangeStart + lastItemMax % 60 + 1}")
            } else { // 最开始的0-59
                AppSettingManager.saveInt(lastItemMax + 1, "quote_range_start")
                Logger.error("---", "下一次起始位置<60->${lastItemMax + 1}")
            }
        } else {
            // 16800条数据使用完毕
            AppSettingManager.saveObject<QuoteBean>(QuoteBean("", "", url, "", ""), "quote_bean")
            AppSettingManager.saveInt(0, "quote_range_start")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        db!!.close()
    }

}
